//
//  LMReadController.m
//  EPA
//
//  Created by lanou3g on 16/4/20.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "LMReadController.h"
#import "LMNetWorkRequestManager.h"
#import "XLPopMenuViewModel.h"
#import "XLPopMenuViewSingleton.h"
#import "XLPopMenuView.h"
#import "DBManager.h"
#import "LMCommentController.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
@interface LMReadController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) NSMutableArray *arr;
///属性存储html
@property (nonatomic, strong) NSString *htmlStr;
@property (nonatomic, strong) NSString *collectBtnTitle;

@end

@implementation LMReadController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.webView.opaque = NO; //不设置这个值 页面背景始终是白色
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    [self loadDataFormID:self.model.ID];
    
    //    分享
    UIBarButtonItem *shareBtn  = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareBtnAction:)];
    //    评论
    UIBarButtonItem *commentBtn  =  [[UIBarButtonItem alloc]initWithTitle:@"评论" style:UIBarButtonItemStylePlain target:self action:@selector(commentBtnAction:)];
    
    //    判断是否收藏过 修改item
    NSString *collectBtnTitle = nil;
    if ([[DBManager shareManager]hasCollect:self.model.ID]) {
        collectBtnTitle = @"取消收藏";
    }else{
        collectBtnTitle= @"收藏";
    }
    //    收藏
    UIBarButtonItem *shoucanBtn  =  [[UIBarButtonItem alloc]initWithTitle:collectBtnTitle style:UIBarButtonItemStylePlain target:self action:@selector(shoucanBtnAction:)];
    self.collectBtnTitle = collectBtnTitle;
    
    [self.navigationItem setRightBarButtonItems:@[shareBtn,commentBtn,shoucanBtn] animated:YES];

}
#pragma mark - 各种方法
//分享方法
- (void)shareBtnAction:(UIBarButtonItem *)item{
    if ([UserInfoManager shareManager].auth) {

    //1、创建分享内容
    UIImage *image = [UIImage imageNamed: @"ba.jpg"];
    NSArray *imageArray = [NSArray arrayWithObject:image];
    //    NSArray* imageArray = @[[UIImage imageNamed:@"32"]];
    //         参数字典
    //    if (imageArray) {
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params SSDKSetupShareParamsByText:@"我要分享" images:imageArray url:[NSURL URLWithString:@"http://www.mob.com/#/"] title:@"来自XX的分享" type:SSDKContentTypeAuto];
    //    }
    //    （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    
    //2、分享（可以弹出我们的分享菜单和编辑界面）
    //    展示分享视图
    [ShareSDK showShareActionSheet:nil items:nil shareParams:params onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        switch (state) {
            case SSDKResponseStateSuccess:
                NSLog(@"分享成功");
                break;
            case SSDKResponseStateFail :
                NSLog(@"分享失败");
                break;
            default:
                break;
        }
    }];
    
    //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
    }else{
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有登录，马上去登陆" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIStoryboard *storyboad = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *loginVC = [storyboad instantiateViewControllerWithIdentifier:@"Login"];
            [self presentViewController:loginVC animated:YES completion:nil];
        }];
        [alertC addAction:yesAction];
        
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:nil];
        [alertC addAction:noAction];
        
        [self presentViewController:alertC animated:YES completion:nil];
    }
    
    
}
//点击评论事件
- (void)commentBtnAction:(UIBarButtonItem *)item{
    LMCommentController *commentVC= [[LMCommentController alloc]init];
    commentVC.connentID = self.model.ID;
    [self.navigationController pushViewController:commentVC animated:YES];
}
//收藏方法
- (void)shoucanBtnAction:(UIBarButtonItem *)item{
    if ([UserInfoManager shareManager].auth) {
        if ([item.title isEqualToString:@"收藏"]) {
            [item setTitle:@"取消收藏"];
            [[DBManager shareManager] collectDetailModel:self.model html:self.htmlStr];
        }else{
            [item setTitle:@"收藏"];
            [[DBManager shareManager]cancelCollectArticle:self.model.ID];
        }

    }else{
        NSLog(@"没有登录");
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有登录，马上去登陆" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIStoryboard *storyboad = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *loginVC = [storyboad instantiateViewControllerWithIdentifier:@"Login"];
            [self presentViewController:loginVC animated:YES completion:nil];
        }];
        [alertC addAction:yesAction];
        
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:nil];
        [alertC addAction:noAction];
        
        [self presentViewController:alertC animated:YES completion:nil];
      
    }
 }

#pragma mark - 解析数据
-(void)loadDataFormID:(NSString *)ID{
    NSDictionary *params = [NSDictionary dictionary];
    if ([UserInfoManager shareManager].auth) {
        params =@{@"contentid":ID,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":[UserInfoManager shareManager].auth,@"version":@"3.0.2"};
    }else{
        params = @{@"contentid":ID,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":@"",@"version":@"3.0.2"};
    }
    [LMNetWorkRequestManager requestURL:[NSURL URLWithString:READCONTENT_URL] Method:LM_POST Params:params Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDict = jsonDict[@"data"];
        NSString *htmlStr = dataDict[@"html"];
//        NSLog(@"%@",htmlStr);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.webView loadHTMLString:htmlStr baseURL:nil];
            self.htmlStr=  htmlStr;
        });
    }];
}




#pragma mark - 加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"加载完成");

    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth=380;" //缩放系数
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height * (maxwidth/oldwidth);"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    

   

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
